package com.tjetc.home_work;


public class _2HomeWork {
    public static void main(String[] args) {
        /*
            1.有一个交通工具接口类Vehicles,有work接口
            2.有Horse类和Boat类分别实现Vehicles
            3.创建交通工具工厂类，有两个方法分别获得交通工具Horse和Boat
            4.有Person类，有name和Vehicles属性，在构造器中为两个属性赋值
            5.实例化Person对象“唐僧”,要求一般情况下用Horse作为交通工具，遇到大河时用Boat作为交通工具
         */
//        Person person = new Person("唐僧", new Horse());
        Person person = new Person("唐僧", VehiclesFactory.getHorse());
        // 走路
        person.common();
        // 要过河
        person.river();
        // 走路
        person.common();

    }
}

class VehiclesFactory {
    // 饿汉式单例
    public static final Horse HORSE = new Horse();

    public static Horse getHorse() {
        return HORSE;
    }


    public static Boat getBoat() {
        return new Boat();
    }
}


interface Vehicles {
    void work();
}

class Horse implements Vehicles{

    @Override
    public void work() {
        System.out.println("骑马走路");
    }
}

class Boat implements Vehicles {

    @Override
    public void work() {
        System.out.println("开船过河");
    }
}

class Person {
    String name;
    Vehicles vehicles;

    public Person(String name, Vehicles vehicles) {
        this.name = name;
        this.vehicles = vehicles;
    }

    public Person() {
    }

    // 一般情况
    public void common() {
        if (!(vehicles instanceof Horse)) {
            vehicles = VehiclesFactory.getHorse();
        }
        vehicles.work();
    }

    // 过河
    public void river() {
        if (!(vehicles instanceof Boat)) {
            vehicles = VehiclesFactory.getBoat();
        }
        vehicles.work();
    }
}
